//
//  HMSettingAddressController.m
//  HMMarket
//
//  Created by 孙鹏飞 on 2017/5/16.
//  Copyright © 2017年 homai. All rights reserved.
//

#import "HMSettingAddressController.h"
#import "AddressTableViewCell.h"
#import "HMAddNewAddressController.h"
#import "HMEditAddressController.h"

#import "MGAddress.h"


@interface HMSettingAddressController () <UITableViewDelegate,UITableViewDataSource,AddressTableViewCellDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView; // 地址表格
@property (weak, nonatomic) IBOutlet UIButton *addAddressBtn; // 添加新地址按钮
@property (nonatomic, strong) NSMutableArray * addressArray; // 地址数组
@property (nonatomic, assign) NSIndexPath * oldIndexPath; // 地址模型

@end

@implementation HMSettingAddressController

- (NSMutableArray *)addressArray
{
    if (_addressArray == nil) {
        _addressArray = [NSMutableArray array];
    }
    return _addressArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.title = @"管理收货地址";
    [self setupTableView];
    [self setupData];
}

- (void)setupTableView
{
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = kBackGolor;
    self.tableView.showsVerticalScrollIndicator = NO;
}

- (void)setupData
{
    // 1. 上传参数
    NSMutableDictionary * param = [NSMutableDictionary dictionary];
    [param setObjOrNil:[MGAccountTool getUid] forKey:@"uid"];

    // 2. 发送请求
    [HttpBaseTool get:kAddressListUrl params:param success:^(id responseObj) {
        // 字典数组 -> 模型数组
        self.addressArray = [MGAddress mj_objectArrayWithKeyValuesArray:responseObj[@"data"]];
      
        // 刷新表格
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        if (error.code != NSURLErrorCancelled) { // 并非是取消任务导致的eror，其他错误导致的
            [HMHUDManager showHUDWithText:NetWorkError];
        }
    }];
}

#pragma mark - tableView代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.addressArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MGAddress * detail = self.addressArray[indexPath.section];
    NSString * str = [NSString stringWithFormat:@"%@%@%@%@",detail.province,detail.city,detail.county,detail.address];
    if ([self getTextHeight:str] > 20) {
        return 132;
    }
    return 112;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AddressTableViewCell * cell = [AddressTableViewCell cellWithTableView:tableView];
    cell.delegate = self;
    cell.indexpath = indexPath;
    cell.address = self.addressArray[indexPath.section];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 5;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 5;
}

#pragma mark - AddressTableViewCellDelegate
- (void)AddressTableViewCell:(AddressTableViewCell *)cell DidClickedIs_defaultBtnAtIndexPath:(NSIndexPath *)indexPath
{
    MGAddress * detail = self.addressArray[indexPath.section];
    if (detail.state) {
        return;
    }
    
    // 1.上传参数
    NSMutableDictionary * param = [NSMutableDictionary dictionary];
    [param setObjOrNil:[MGAccountTool getUid] forKey:@"user_id"];
    [param setObjOrNil:detail.address_id forKey:@"address_id"];
    // 2. 发送请求
    [HttpBaseTool get:kDefaultAddressUrl params:param success:^(id responseObj) {
        if ([responseObj[@"code"] integerValue] == 200) {
            [HMHUDManager showHUDWithText:@"设置默认地址成功"];
            for (MGAddress * deta in self.addressArray) {
                if (deta.state) {
                    deta.state = NO;
                }
            }
            detail.state = YES;
            [self.tableView reloadData];
        }
        
    } failure:^(NSError *error) {
        if (error.code != NSURLErrorCancelled) { // 并非是取消任务导致的eror，其他错误导致的
            [HMHUDManager showHUDWithText:NetWorkError];
        }
    }];
}

-(void)AddressTableViewCell:(AddressTableViewCell *)cell DidClickedEditBtnAtIndexPath:(NSIndexPath *)indexPath
{
    HMEditAddressController * vc = [[HMEditAddressController alloc] init];
    vc.addressMessage = self.addressArray[indexPath.section];
    __weak typeof(self) weakSelf = self;
    vc.popBlock = ^{
        [weakSelf setupData];
    };
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)AddressTableViewCell:(AddressTableViewCell *)cell DidClickedDeleteBtnAtIndexPath:(NSIndexPath *)indexPath
{
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"是否删除地址" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * action = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    
        MGAddress * detail = self.addressArray[indexPath.section];
        // 1.上传参数
        NSMutableDictionary * param = [NSMutableDictionary dictionary];
        [param setObjOrNil:detail.address_id forKey:@"address_id"];
        
        // 2. 发送请求
        [HttpBaseTool post:kDeleteAddressUrl params:param success:^(id responseObj) {
            if ([responseObj[@"code"] integerValue] == 200) {
                [HMHUDManager showHUDWithText:@"地址删除成功"];
                [self setupData];
            }
        } failure:^(NSError *error) {
            if (error.code != NSURLErrorCancelled) { // 并非是取消任务导致的eror，其他错误导致的
                [HMHUDManager showHUDWithText:NetWorkError];
            }
        }];
        
    }];
    UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:action];
    [alert addAction:action1];
    [self presentViewController:alert animated:YES completion:nil];
}

- (CGFloat)getTextHeight:(NSString *)str
{
    NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:14]};
    CGSize size = [str boundingRectWithSize:CGSizeMake(KWidthSCREEN - 26, MAXFLOAT) options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
    return size.height;
}

- (IBAction)addNewAddress:(id)sender { // 添加新地址按钮点击
    HMAddNewAddressController * vc = [[HMAddNewAddressController alloc] init];
    __weak typeof(self) weakSelf = self;
    vc.popBlock = ^{
        [weakSelf setupData];
        if ([_delegate respondsToSelector:@selector(refreshData)]) {
            [_delegate refreshData];
        }
        if (_refresh != nil) {
            _refresh(@"");
        }
//        !_refresh?:;
    };
    [self.navigationController pushViewController:vc animated:YES];
}

@end
